import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/match/detail/match_intelligence_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/ads_label.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';

import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/card.dart';
import '../../pick/secret/secret_item.dart';

class LqInfoWidget extends StatefulWidget {
  const LqInfoWidget({Key? key}) : super(key: key);

  @override
  State<LqInfoWidget> createState() => _LqInfoWidgetState();
}

class _LqInfoWidgetState extends State<LqInfoWidget> {
  final logic = Get.put(LqMatchInfoLogic(), tag: '${Get.arguments}');

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LqMatchInfoLogic>(
        tag: '${Get.arguments}',
        builder: (logic) => LoadingWidget<int>(
              isLoading: false,
              data: logic.data?.toJson().values.map((e) => e).toList().join(),
              child: () => SingleChildScrollView(
                physics: const ClampingScrollPhysics(),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const AdsLabel(
                      adsTag: "match_lq_爆料",
                      tapType: 'ggw_bsxq_bl',
                      margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
                    ),
                    Container(height: 8),
                    block<bool>(
                        data: logic.secret.noValue,
                        child: secret()
                    ),
                    block<String>(
                        data: (logic.data?.homeInjury ?? "") +
                            (logic.data?.guestInjury ?? ""),
                        child: suspend()),
                    block<int>(
                        data: logic.totalLength, child: _intelligence()),
                    Container(height: 60)
                  ],
                ),
              ),
            ));
  }

  Widget block<T>({required T data, required Widget child}) {
    return LoadingWidget<T>(
      isLoading: false,
      data: data,
      noData: Container(),
      child: () => Container(
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
        margin: const EdgeInsets.only(bottom: 10, left: 8, right: 8),
        child: child,
      ),
    );
  }

  Widget secret(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 4),
            Image.asset(
                width: 24, Utils.getImgPath("match_info_secret.png")),
            Container(width: 2),
            QkdText("海外情报", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        if(logic.secret?.where((e) => e.canRead != true).toList().length.hasValue == true)
        SecretItem.detail(
          count: logic.secret?.where((e) => e.canRead != true).toList().length,
          onChange: (change) {
            if(change == true) logic.getData();
          }
        ).paddingOnly(bottom: 8),
        ...logic.secret?.where(
          (element) => element.canRead == true
        ).map<Widget>(
          (e) => SecretItem.detail(
            secret: e,
            onChange: (change) {
              if(change == true) logic.getData();
            }
          )
        ).toList().insertEvery(Container(height: 8)) ?? []
      ],
    );
  }

  Widget _intelligence() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 8),
            Image.asset(
                width: 24, Utils.getImgPath("match_info_important.png")),
            Container(width: 4),
            QkdText("重要情报", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        TabBlock(
          tabs: List.generate(2, (index) => tabHead(index == 0 ? true : false)),
          pages: List.generate(
            2, (index) => Padding(
              padding: const EdgeInsets.symmetric(
                  horizontal: 12, vertical: 16),
              child: Column(
                children: [
                  _intelligenceContent(logic.intelligence?[index == 0?1:0],
                      name: "有利情报"),
                  Container(height: 8),
                  _intelligenceContent(logic.intelligence?[4],
                      name: "中立情报"),
                  Container(height: 8),
                  _intelligenceContent(logic.intelligence?[index==0?3:2],
                      name: "不利情报")
                ],
              ),
            )))
      ],
    );
  }

  Widget _intelligenceContent(List? data, {String? name, Widget? asset}) {
    return data == null || data.isEmpty
        ? Container()
        : Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(children: [
                if (asset != null)
                  Container(
                      width: 20,
                      height: 20,
                      margin: const EdgeInsets.only(right: 5),
                      child: asset),
                if (name != null)
                  Padding(
                    padding: EdgeInsets.only(bottom: 10),
                    child: QkdText(name,
                        needCenter: true,fontWeight: FontWeight.w500),
                  ),
              ]),
              Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: List.generate(
                      data.length,
                      (index) => data[index] != ""
                          ? _paragraph(data[index])
                          : Container()))
            ],
          );
  }

  Widget suspend() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 8),
            Image.asset(width: 24, Utils.getImgPath("match_info_suspend.png")),
            Container(width: 4),
            QkdText("球员变动", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        Block(
          child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
          child: Column(children: [
            Row(children: [
              Expanded(child: suspendHead(true)),
              Expanded(child: suspendHead(false))
            ]),
            Container(height: 10),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(child: suspendList(logic.guestSuspend, false)),
                Container(width: 10),
                Expanded(child: suspendList(logic.homeSuspend, true))
              ],
            ),
            Container(height: 10),
            _intelligenceContent(
                logic.data?.injuryAnalysis?.split(RegExp(r"[\f\r\n\t\v]+")),
                name: "伤停解读"),
          ]),
        ))
      ],
    );
  }

  Widget tabHead(bool isHome) {
    return Row(mainAxisSize: MainAxisSize.min, children: [
      CachedNetworkImage(
          width: 20,
          height: 20,
          fit: BoxFit.fitWidth,
          errorWidget: (
            context,
            url,
            error,
          ) =>
              Image.asset(Utils.getImgPath("lq_placeholder.png")),
          placeholder: (context, url) => Styles.placeholderIcon(),
          imageUrl: isHome
              ? logic.detail?.awayTeamLogo ?? ""
              : logic.detail?.homeTeamLogo ?? ""),
      Container(width: 4),
      QkdText(isHome
          ? logic.detail?.awayTeamName ?? ""
          : logic.detail?.homeTeamName ?? ""),
    ]);
  }

  Widget _dot() {
    return Container(
        width: 10,
        height: 4,
        alignment: Alignment.centerLeft,
        decoration:
            const BoxDecoration(shape: BoxShape.circle, color: Colours.main));
  }

  Widget _paragraph(String text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 10, right: 3),
            child: _dot(),
          ),
          Flexible(
              child: QkdText(
            text.split(" ").join().split("").join("\u200A").trim(),
            height: 1.6,
            color: Color(0xFF444444),
            letterSpacing: -0.3,
            textAlign: TextAlign.justify,
          )),
        ],
      ),
    );
  }

  Widget suspendHead(bool isHome) {
    var list = [
      CachedNetworkImage(
          width: 32,
          height: 32,
          errorWidget: (
            context,
            url,
            error,
          ) =>
              Image.asset(Utils.getImgPath("lq_placeholder.png")),
          placeholder: (context, url) => Styles.placeholderIcon(),
          imageUrl: isHome
              ? logic.detail?.awayTeamLogo ?? ""
              : logic.detail?.homeTeamLogo ?? ""),
      Container(width: 4),
      QkdText(
          isHome
              ? logic.detail?.awayTeamName ?? ""
              : logic.detail?.homeTeamName ?? "")
    ];
    return Row(
      mainAxisAlignment:
          isHome ? MainAxisAlignment.start : MainAxisAlignment.end,
      children: isHome ? list : list.reversed.toList(),
    );
  }

  Widget suspendList(List<List<String>> data, bool isHome) {
    return LoadingWidget<int>(
      isLoading: false,
      data: data.length,
      noData: Container(
        alignment: Alignment.topCenter,
        padding: const EdgeInsets.symmetric(vertical: 18),
        child: QkdText('暂无数据',fontSize: 11, color: Colours.grey99),
      ),
      child: () => Column(
        children: List.generate(
            data.length,
            (index) => Padding(
                  padding:
                      EdgeInsets.only(bottom: index < data.length - 1 ? 4 : 0),
                  child: suspendPlayer(data[index], isHome),
                )),
      ),
    );
  }

  Widget suspendPlayer(List<String>? list, bool isHome) {
    return (list?.length ?? 0) < 4
        ? Container()
        : Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(height: 4),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(child: QkdText(list?[0] ?? "")),
                  Container(
                    height: 14,
                    padding: const EdgeInsets.symmetric(horizontal: 2),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: isHome ? Colours.main : Colours.blue2766D6,
                        borderRadius:
                            const BorderRadius.all(Radius.circular(2))),
                    child: QkdText(
                      list?[2] ?? "",
                      needCenter: true,
                      fontSize: 10, color: Colours.white, height: 1,
                    ),
                  )
                ],
              ),
              Container(height: 8),
              RichText(
                  softWrap: true,
                  strutStyle: Styles.centerStyle(fontSize: 10),
                  text: TextSpan(children: [
                    WidgetSpan(
                        child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                            height: 14,
                            padding: const EdgeInsets.symmetric(horizontal: 2),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                border: Border.all(
                                    width: 0.5,
                                    color: isHome
                                        ? Colours.blue2766D6
                                        : Colours.blue2766D6),
                                borderRadius:
                                    const BorderRadius.all(Radius.circular(2))),
                            child: QkdText(
                              list?[1] ?? "",
                              needCenter: true,
                              fontSize: 10,
                              color: isHome
                                  ? Colours.blue2766D6
                                  : Colours.blue2766D6,
                              height: 1,
                            )),
                      ],
                    ).paddingOnly(right: 2)),
                    TextSpan(
                      text: list?[3] ?? "",
                      style:
                          const TextStyle(fontSize: 11, color: Colours.grey99),
                    )
                  ]))
            ],
          );
  }
}
